const axios = require('axios');

const BASE_URL = 'http://localhost:4000/api/knowledge-base';
let authToken = '';

// 测试用户登录
async function testLogin() {
  console.log('🔐 测试用户登录...');
  try {
    const response = await axios.post(`http://localhost:4000/api/auth/login`, {
      username: 'admin',
      password: 'admin123'
    });
    
    if (response.data.data && response.data.data.token) {
      authToken = response.data.data.token;
      console.log('✅ 登录成功，获取到token');
      return true;
    } else {
      console.log('❌ 登录响应中没有token');
      console.log('   响应结构:', JSON.stringify(response.data, null, 2));
      return false;
    }
  } catch (error) {
    console.log('❌ 登录失败:', error.response?.data?.message || error.message);
    console.log('   错误详情:', error.response?.data || error.message);
    console.log('   状态码:', error.response?.status);
    return false;
  }
}

// 测试创建知识库
async function testCreateKnowledge() {
  console.log('\n📚 测试创建知识库...');
  try {
    const response = await axios.post(`${BASE_URL}/`, {
      title: '测试知识库',
      description: '这是一个测试知识库',
      content: '这是测试知识库的内容',
      status: 'DRAFT'
    }, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 创建知识库成功');
    console.log('   响应数据:', response.data);
    return response.data.data.id;
  } catch (error) {
    console.log('❌ 创建知识库失败:', error.response?.data?.message || error.message);
    return null;
  }
}

// 测试获取知识库列表
async function testGetKnowledgeList() {
  console.log('\n📋 测试获取知识库列表...');
  try {
    const response = await axios.get(`${BASE_URL}/`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 获取知识库列表成功');
    console.log('   总数:', response.data.total);
    console.log('   列表长度:', response.data.data.length);
    return response.data.data;
  } catch (error) {
    console.log('❌ 获取知识库列表失败:', error.response?.data?.message || error.message);
    return [];
  }
}

// 测试获取单个知识库
async function testGetKnowledge(id) {
  console.log('\n🔍 测试获取单个知识库...');
  try {
    const response = await axios.get(`${BASE_URL}/${id}`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 获取知识库成功');
    console.log('   标题:', response.data.title);
    console.log('   描述:', response.data.description);
    return response.data;
  } catch (error) {
    console.log('❌ 获取知识库失败:', error.response?.data?.message || error.message);
    return null;
  }
}

// 测试更新知识库
async function testUpdateKnowledge(id) {
  console.log('\n✏️ 测试更新知识库...');
  try {
    const response = await axios.put(`${BASE_URL}/${id}`, {
      title: '更新后的测试知识库',
      description: '这是更新后的描述',
      content: '这是更新后的内容',
      status: 'DRAFT'
    }, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 更新知识库成功');
    console.log('   新标题:', response.data.title);
    console.log('   新描述:', response.data.description);
    return response.data;
  } catch (error) {
    console.log('❌ 更新知识库失败:', error.response?.data?.message || error.message);
    return null;
  }
}

// 测试删除知识库
async function testDeleteKnowledge(id) {
  console.log('\n🗑️ 测试删除知识库...');
  try {
    const response = await axios.delete(`${BASE_URL}/${id}`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 删除知识库成功');
    console.log('   响应数据:', response.data);
    return true;
  } catch (error) {
    console.log('❌ 删除知识库失败:', error.response?.data?.message || error.message);
    return false;
  }
}

// 测试搜索知识库
async function testSearchKnowledge() {
  console.log('\n🔎 测试搜索知识库...');
  try {
    const response = await axios.get(`${BASE_URL}/?search=测试`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 搜索知识库成功');
    console.log('   搜索结果数:', response.data.total);
    console.log('   搜索关键词: 测试');
    return response.data;
  } catch (error) {
    console.log('❌ 搜索知识库失败:', error.response?.data?.message || error.message);
    return null;
  }
}

// 测试按分类获取知识库
async function testGetKnowledgeByCategory() {
  console.log('\n📂 测试按分类获取知识库...');
  try {
    const response = await axios.get(`${BASE_URL}/?categoryId=技术`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 按分类获取知识库成功');
    console.log('   分类: 技术');
    console.log('   数量:', response.data.total);
    return response.data;
  } catch (error) {
    console.log('❌ 按分类获取知识库失败:', error.response?.data?.message || error.message);
    return null;
  }
}

// 测试获取知识库统计
async function testGetKnowledgeStats() {
  console.log('\n📊 测试获取知识库统计...');
  try {
    const response = await axios.get(`${BASE_URL}/stats/overview`, {
      headers: { Authorization: `Bearer ${authToken}` }
    });
    
    console.log('✅ 获取知识库统计成功');
    console.log('   总知识库数:', response.data.data.totalKnowledgeBases);
    console.log('   已发布知识库数:', response.data.data.publishedKnowledgeBases);
    console.log('   草稿知识库数:', response.data.data.draftKnowledgeBases);
    return response.data;
  } catch (error) {
    console.log('❌ 获取知识库统计失败:', error.response?.data?.message || error.message);
    return null;
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始测试知识库管理接口\n');
  
  // 登录
  if (!await testLogin()) {
    console.log('❌ 登录失败，无法继续测试');
    return;
  }
  
  // 创建知识库
  const knowledgeId = await testCreateKnowledge();
  if (!knowledgeId) {
    console.log('❌ 创建知识库失败，无法继续测试');
    return;
  }
  
  // 获取知识库列表
  await testGetKnowledgeList();
  
  // 获取单个知识库
  await testGetKnowledge(knowledgeId);
  
  // 更新知识库
  await testUpdateKnowledge(knowledgeId);
  
  // 搜索知识库
  await testSearchKnowledge();
  
  // 按分类获取知识库
  await testGetKnowledgeByCategory();
  
  // 获取统计信息
  await testGetKnowledgeStats();
  
  // 删除知识库
  await testDeleteKnowledge(knowledgeId);
  
  console.log('\n🎉 所有知识库接口测试完成！');
}

// 运行测试
runTests().catch(console.error);
